<template>
  <div>
    <Upload
        class="upload-demo"
        :action="action"

        :max-size="maxSize"
        :disabled="disabled"
        :multiple="multiple"
        :limit="limit"
        :paste="true"
        :headers="uploadHeader"
        :accept="accept"
        :list-type="listType"
        :with-credentials="withCredentials"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :on-preview="handlePreview"
        :auto-upload="autoUpload"
        :default-file-list="fileList">
      <Button v-if="listType != 'picture-card'" size="small" type="primary">选取文件</Button>
      <i v-else class="el-icon-plus"></i>
      <div v-if="tip != undefined" slot="tip" class="el-upload__tip">请选择图片，且不超过500kb</div>
    </Upload>
  </div>
</template>
<script>
export default {
  name: 'FormUpload',
  data() {
    return {
      fileList: [],
    };
  },
  props: {
    value: {
      type: Array,
      default: () => [],
      required: true,
    },
    action: {
      type: String,
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },

    multiple: {
      type: Boolean,
      default: false,
    },

    accept: {
      type: String,
    },
    listType: {
      type: String,
      default: 'text',
    },
    limit: {
      type: Number,
    },

    withCredentials: {
      type: Boolean,
      default: false,
    },

    autoUpload: {
      type: Boolean,
      default: true,
    },

    tip: {
      type: String,
    },

    drag: {
      type: Boolean,
      default: false,
    },
    record: {
      type: Object,
    },
  },
  watch: {
    value(val) {
      if (val && val.length > 0) {
        const valueNames = val.map(t => t.name).join(',');
        const fileListNames = this.fileList.map(t => t.name).join(',');
        if (fileListNames != valueNames) {
          this.fileList = val;
        }
      }
    },
  },
  computed: {

    uploadHeader() {
      if (this.record && this.record.options && this.record.options.headers) {
        const hs = {};
        this.record.options.headers.forEach(t => {
          hs[t.label] = t.value;
        });

        return hs;
      }
      return {};
    },

    uploadResponseFileUrl() {
      if (this.record && this.record.options && this.record.options.responseFileUrl) {

        return this.record.options.responseFileUrl;
      }

      return null;
    },
    maxSize() {
      if (this.record && this.record.options && this.record.options.limitSize) {
        return this.record.options.limitSize * 1024;
      }
      return null;
    },
  },
  mounted() {
    if (this.value == null || this.value == undefined) {

      this.fileList = [];
    } else {
      this.fileList = this.value;
    }
  },
  methods: {
    beforeUpload(file) {
      const fileName = file.name;

      const ltSize = file.size / 1024 / 1024;

      const index1 = fileName.lastIndexOf('.');

      const index2 = fileName.length;
      const fileSuffix = fileName.substring(index1 + 1, index2);

      const fileType = file.type;
      if (
          this.accept &&
          this.accept.indexOf('image') >= 0 &&
          !this.isAssetTypeAnImage(fileSuffix)
      ) {
        this.$message.error('当前图片格式只支持:[png,jpg,jpeg,bmp]');
        return false;
      }

      if (this.record.options.limitSize && ltSize > this.record.options.limitSize) {
        this.$message.error('上传文件大小不能超过' + (this.record.options.limitSize) + 'MB!');

        return false;

      }
      return true;
    },
    isAssetTypeAnImage(ext) {
      return ['png', 'jpg', 'jpeg', 'bmp'].indexOf(ext.toLowerCase()) !== -1;
    },
    handleSuccess(response, file, fileList) {

      const responseFileUrl = this.uploadResponseFileUrl;


      const objectPath = require('object-path');
      const fileUrl = objectPath.get(response, responseFileUrl);

      if (fileUrl) {

        const f_ = {name: file.name, size: file.size, url: fileUrl};
        const addData = [
          ...this.value,
          {
            name: file.name, size: file.size, url: fileUrl,
          },
        ];

        this.$emit('input', addData);
      }


    },
    handleRemove(file, fileList) {

      const name = file.name;


      this.$emit(
          'input',
          this.value.filter(val => val.name != name),
      );
    },

    handlePreview(file) {

      if (file.url) {
        window.location.href = file.url;
      } else {
        this.$message.error('找不到文件下载路径');
      }

    },
  },
};
</script>
